import React, { useEffect, useState } from 'react';
import './index.css'
import { Button, Modal } from 'antd';
import TabSwitcher from '../../components/YiQiXiu/TabSwitcher';
import FileUploader from '../../components/YiQiXiu/FileUploader';
import ProgressBar from '../../components/YiQiXiu/ProgressBar';
import MediaList from '../../components/YiQiXiu/MediaList';
import ImageSwitcher from '../../components/YiQiXiu/ImageSwitcher';
import { MediaState, MediaItem } from '../../components/types';

const App: React.FC = () => {
    const [media, setMedia] = useState<MediaState>({ images: [], videos: [], music: [] });
    const [activeTab, setActiveTab] = useState<'images' | 'videos' | 'music'>('images');
    const maxMemory = 300; // 最大内存300MB
    const [currentMemory, setCurrentMemory] = useState<number>(0);
    const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [batchMode, setBatchMode] = useState(false); // 批量管理模式的状态


    useEffect(() => {
        const storedMedia = localStorage.getItem('media');
        if (storedMedia) {
            setMedia(JSON.parse(storedMedia));
        }
    }, []);

    useEffect(() => {
        localStorage.setItem('media', JSON.stringify(media));

        const totalMemory = media.images.reduce((sum, item) => sum + (item.size || 0), 0)
            + media.videos.reduce((sum, item) => sum + (item.size || 0), 0)
            + media.music.reduce((sum, item) => sum + (item.size || 0), 0);

        setCurrentMemory(parseFloat((totalMemory / (1024 * 1024)).toFixed(2)));
    }, [media]);

    const handleUpload = (type: 'images' | 'videos' | 'music', file: MediaItem) => {
        setMedia(prev => {
            const updatedMedia = {
                ...prev,
                [type]: [...prev[type], file],
            };
            const newTotalMemory = updatedMedia.images.reduce((sum, item) => sum + (item.size || 0), 0)
                + updatedMedia.videos.reduce((sum, item) => sum + (item.size || 0), 0)
                + updatedMedia.music.reduce((sum, item) => sum + (item.size || 0), 0)
                + (file.size || 0);

            setCurrentMemory(parseFloat((newTotalMemory / (1024 * 1024)).toFixed(2)));
            return updatedMedia;
        });
    };

    const deleteItem = (type: 'images' | 'videos' | 'music', id: string) => {
        setMedia(prev => ({
            ...prev,
            [type]: prev[type].filter(item => item.id !== id),
        }));
        selectedIds.delete(id);
        setSelectedIds(new Set(selectedIds));
    };

    const deleteSelectedItems = (type: 'images' | 'videos' | 'music') => {
        setMedia(prev => ({
            ...prev,
            [type]: prev[type].filter(item => !selectedIds.has(item.id)),
        }));
        setSelectedIds(new Set());
    };

    const toggleSelect = (id: string) => {
        setSelectedIds(prev => {
            const newSelected = new Set(prev);
            if (newSelected.has(id)) {
                newSelected.delete(id);
            } else {
                newSelected.add(id);
            }
            return newSelected;
        });
    };

    const toggleSelectAll = () => {
        const allIds = media[activeTab].map(item => item.id);
        setSelectedIds(prev => {
            if (prev.size === allIds.length) {
                return new Set();
            } else {
                return new Set(allIds);
            }
        });
    };

    const isSelected = (id: string) => selectedIds.has(id);

    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    const toggleBatchMode = () => {
        setBatchMode(prev => !prev);
        setSelectedIds(new Set());
    };

    return (
        <div style={{ width: '80%', height: '80%', border: 'solid 3px #f00', position: 'absolute', left: '10%', top: '10%' }}>
            <TabSwitcher activeTab={activeTab} setActiveTab={setActiveTab} />

            <MediaList
                media={media[activeTab]}
                activeTab={activeTab}
                deleteItem={deleteItem}
                toggleSelect={toggleSelect}
                isSelected={isSelected}
            />

            {/* 只有在非批量管理模式时显示进度条和上传按钮 */}
            {!batchMode && (
                <>
                    <ProgressBar currentMemory={currentMemory} maxMemory={maxMemory} />

                    <div>
                        <Button style={{ position: 'absolute', right: '20%', top: '16%' }} type="primary" onClick={showModal}>
                            上传素材
                        </Button>
                        <Modal footer={null} title="上传素材" open={isModalOpen} onCancel={handleCancel} width={960}>
                            <div style={{ width: '900px', height: '450px' }}>
                                <FileUploader
                                    type="music"
                                    onUpload={file => handleUpload('music', file)}
                                    uploadedFiles={media.music || []}
                                />
                                <FileUploader
                                    type="video"
                                    onUpload={file => handleUpload('videos', file)}
                                    uploadedFiles={media.videos || []}
                                />
                                <FileUploader
                                    type="image"
                                    onUpload={file => handleUpload('images', file)}
                                    uploadedFiles={media.images || []}
                                />
                            </div>
                        </Modal>
                    </div>
                </>
            )}

            <div style={{ width: '100%', height: '35px' }}>
                {!batchMode && (
                    <button onClick={toggleBatchMode} style={{ position: 'absolute', right: '10%', top: '17%', border: '0', backgroundColor: '#fff', fontSize: '17px' }}>
                        批量管理
                    </button>
                )}
                {batchMode && (
                    <button onClick={() => deleteSelectedItems(activeTab)} style={{ position: 'absolute', right: '15%', top: '18%', border: '0', backgroundColor: '#fff', fontSize: '17px' }} disabled={selectedIds.size === 0}>
                        删除
                    </button>
                )}
                {batchMode && (
                    <div style={{ display: 'flex', alignItems: 'center', position: 'absolute', right: '20%', top: '18%' }}>
                        <label style={{ display: 'flex', alignItems: 'center' }}>
                            <input
                                style={{ width: '16px', height: '16px', marginRight: '4px' }}
                                type="checkbox"
                                checked={media[activeTab].length > 0 && selectedIds.size === media[activeTab].length}
                                onChange={toggleSelectAll}
                            />
                            <span style={{ fontSize: '16px' }}>全选</span>
                        </label>
                        <div style={{ marginLeft: '10px' }}>已选择 {selectedIds.size} 个素材</div>
                    </div>
                )}
                {batchMode && (
                    <button onClick={toggleBatchMode} style={{ position: 'absolute', right: '10%', top: '18%', border: '0', backgroundColor: '#fff', fontSize: '17px' }}>
                        完成
                    </button>
                )}
            </div>
            <div className="App">
                <h1>鼠标滑过切换图片</h1>
                <ImageSwitcher />
            </div>
        </div>
    );
};

export default App;